import * as nodeFileSystem from "fs";
import {FilePath} from "./FilePath";
import {ArrayEnhance} from "./ArrayEnhance";

export class FileSystem {
    public static readonly nodeModule = nodeFileSystem;
    constructor() {
    }
    public static getAllFilesFrom(dirname: string): Promise<string[]> {
        return nodeFileSystem.promises.readdir(dirname).then((list: string[]) => {
            const filePromiseList: Array<Promise<string[]>> = [];
            list.forEach((item: string) => {
                const itemFullPath = FilePath.posixJoin(dirname, item);
                const promise = nodeFileSystem.promises.lstat(itemFullPath).then((itemStat) => {
                    const itemPromiseList: Array<Promise<string | string[]>> = [];
                    if (itemStat.isFile()) {
                        itemPromiseList.push(Promise.resolve(itemFullPath));
                    } else if (itemStat.isDirectory()) {
                        itemPromiseList.push(FileSystem.getAllFilesFrom(itemFullPath));
                    }
                    return Promise.all(itemPromiseList).then((resultList: Array<string | string[]>) => {
                        return ArrayEnhance.staticFlatArray(resultList);
                    });
                });
                filePromiseList.push(promise);
            });
            return Promise.all(filePromiseList).then((strArrArr) => {
                return ArrayEnhance.staticFlatArray(strArrArr);
            });
        });
    }
}
